package rwt.server.handlers.web;

import rwt.server.*;
import rwt.server.RailroadMessages.LocoAdrMsg;
import rwt.server.WebMessages.OpenThrottleRequest;
import rwt.server.WebMessages.OpenThrottleResponse;
import rwt.server.WebMessages.PutAvailableTrains;
import rwt.server.core.*;
import rwt.server.railroad.*;
import rwt.server.railroad.Train.ThrottleStatus;

public class OpenThrottleRequestHandler extends MessageHandler<OpenThrottleRequest>
{
	@Override
	public void handle(OpenThrottleRequest message, IConnection source) throws Exception
	{
		if (!(source instanceof IClient))
			throw new IllegalArgumentException("OpenThrottleRequest did not come from a client.");
		
		IClient sourceClient = (IClient) source;
		int clientId = sourceClient.getId();
		
		boolean granted = false;
		Train t = RailServer.getTrainManager().getTrainById(message.trainId);
		if (t == null)
		{
			// Client passed a bad train number (physical address)
			OpenThrottleResponse response = new OpenThrottleResponse(message.trainId, 0, false, false);
			source.write(response);
			return;
		}
		
		boolean emergency = false;
		if (!message.direct) // BASIC THROTTLE
		{
			if (t.isInitialized() && t.getThrottleStatus() == ThrottleStatus.NONE)
			{
				granted = true;
				t.openThrottle(clientId, ThrottleStatus.BASIC_THROTTLE);
			}
			
			OpenThrottleResponse response = new OpenThrottleResponse(message.trainId, t.getVirtualAddress(), granted, emergency);
			source.write(response);
			
			if (granted)
			{
				PutAvailableTrains availableTrainsMsg = RailServer.getTrainManager().getPutAvailableTrains();
				RailServer.getClientManager().sendToAll(availableTrainsMsg);
			}
		}
		else // EMERGENCY THROTTLE
		{
			granted = true;
			emergency = true;
			t.openThrottle(clientId, ThrottleStatus.EMERGENCY_THROTTLE);
			
			LocoAdrMsg msg = new LocoAdrMsg(message.trainId);
			RailServer.getRailroadServer().write(msg);
			
			// OpenThrottleResponse for Emergency Throttle not sent until we get SlRdDataMsg from the railroad.
			// See SlRdDataHandler.java.
		}
	}
}
